import { computed, ref } from "vue";

export default function useEditTodo(todoListRef) {
	let editingTodoRef = ref(null);

	let initialText = "";

	function edit(todoItem) {
		initialText = todoItem.title;
		editingTodoRef.value = todoItem;
	}
	function doneEdit() {
		let id = editingTodoRef.value.id;
		editingTodoRef.value.title = editingTodoRef.value.title.trim();
		// 如果编辑后内容为空，则删除该todo
		if (!editingTodoRef.value.title) {
			todoListRef.value = todoListRef.value.filter((item) => item.id != id);
		}
		editingTodoRef.value = null;
	}
	function cancelEdit() {
		editingTodoRef.value.title = initialText;
		editingTodoRef.value = null;
	}

	/**
	 * 由于双击显示input元素时，不会自动聚焦，这里手动进行聚焦
	 * @param {DOM} dom
	 */
	function autoFocus(dom) {
		dom.focus();
	}

	let isAllDoneRef = computed({
		set: (value) => {
			// 当计算属性发生改变时，改变todoListRef中所有项的isFinish值
			todoListRef.value.forEach((item) => {
				item.isFinish = value;
			});
		},
		get: () => {
			return todoListRef.value.every((i) => i.isFinish);
		},
	});

	return {
		editingTodoRef,
		edit,
		doneEdit,
		autoFocus,
		cancelEdit,
		isAllDoneRef,
	};
}
